<template>
  <BasicForm @register="registerForm" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, unref, watch, nextTick, onUnmounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../GoodsSearch.data';
  import { useCategoryCustomFields } from '../GoodsSearch.data';
  // Emits声明
  const emit = defineEmits(['register', 'handleOk', 'error']);
  // 存储表单实例
  let formInstance = null;
  // 内部 isUpdate 状态
  const internalIsUpdate = ref(false);
  // 定义 props 接收父组件传递的值
  const props = defineProps({
    isUpdate: {
      type: Boolean,
      default: false,
    },
    record: {
      type: Object,
      default: () => ({}),
    },
  });
  // 使用自定义字段功能
  const { updateFormSchemaWithCustomFields } = useCategoryCustomFields();

  //表单配置
  const [registerForm, { setFieldsValue, getFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });

  // 设置表单值
  function setFormValues(values: any) {
    //console.log('设置表单值1', values, props.record);
    if (values.goodsInfo) {
      const parsedData = JSON.parse(values.goodsInfo);
      // 处理布尔值
      const processedData = processDataAfterLoad({
        id: values.id,
        goodsCode: values.goodsCode,
        ...parsedData,
      });
      setFieldsValue(processedData);
    }
  }

  // 在加载数据时处理布尔值转换
  function processDataAfterLoad(data) {
    const processedData = { ...data };

    // 处理存货属性字段，确保它们正确显示在表单中
    const booleanFields = ['isEshop', 'isPurchase', 'isSale', 'isMadeSelf', 'isMaterial', 'isLaborCost', 'isMadeRequest'];

    booleanFields.forEach((field) => {
      if (field in processedData) {
        // 将字符串形式的布尔值转换为真正的布尔值
        if (processedData[field] === 'true' || processedData[field] === 'True') {
          processedData[field] = true;
        } else if (processedData[field] === 'false' || processedData[field] === 'False') {
          processedData[field] = false;
        }
      }
    });

    return processedData;
  }
  // 设置更新模式
  function setIsUpdate(value: boolean) {
    internalIsUpdate.value = value;
  }
  // 重置表单
  function resetForm() {
    resetFields();
  }
  // 获取当前分类ID
  function getCategoryId() {
    const values = getFieldsValue();
    return values.categoryId;
  }
  watch(
    () => props.record,
    (newRecord) => {
      if (newRecord && Object.keys(newRecord).length > 0) {
        console.log('接收到新的record数据:', newRecord);
        setFormValues(newRecord);

        // 当record数据更新后，检查是否有categoryId并加载自定义字段
        if (newRecord.categoryId) {
          nextTick(() => {
            if (newRecord) {
              updateFormSchemaWithCustomFields(newRecord.categoryId);
            }
          });
        }
      }
    },
    { immediate: true, deep: true }
  );
  // 修改 onMounted 确保 formInstance 总是能被正确初始化
  onMounted(async () => {
    // 如果已经有 record 数据，则处理它
    if (props.record && Object.keys(props.record).length > 0) {
      setFieldsValue(props.record);
      console.log('获取产品分类的值', props.record.categoryId);

      // 如果有分类ID，加载对应的自定义字段
      if (props.record.categoryId) {
        await nextTick();
        updateFormSchemaWithCustomFields(props.record.categoryId);
        console.log('初始化表单值2', props.record);
      }
    }
  });
  // 改进分类字段变化监听器
  const categoryWatcher = watch(
    () => getFieldsValue(),
    async (newValues, oldValues) => {
      console.log('表单字段变化', newValues, oldValues);

      if (newValues && newValues.categoryId) {
        // 检查是否是第一次选择分类或者分类发生了变更
        const shouldUpdateCustomFields = !oldValues || !oldValues.categoryId || newValues.categoryId !== oldValues?.categoryId;

        if (shouldUpdateCustomFields) {
          console.log('分类变更为', newValues.categoryId);
          await nextTick();

          // 确保 formInstance 已经初始化
          if (formInstance) {
            try {
              updateFormSchemaWithCustomFields(formInstance, newValues.categoryId);
              console.log('自定义字段更新成功');
              console.log('更新后的表单结构:', getSchema());
            } catch (error) {
              console.error('更新自定义字段时出错:', error);
            }
          } else {
            console.warn('formInstance尚未初始化，稍后重试');
            // 如果 formInstance 还未初始化，等待一段时间后重试
            setTimeout(() => {
              if (formInstance) {
                updateFormSchemaWithCustomFields(formInstance, newValues.categoryId);
                console.log('延迟更新自定义字段成功');
              }
            }, 100);
          }
        }
      }
    },
    { deep: true }
  );
  // 添加一个新的暴露方法
  function refreshCustomFields() {
    if (formInstance) {
      const currentValues = getFieldsValue();
      if (currentValues && currentValues.categoryId) {
        updateFormSchemaWithCustomFields(currentValues.categoryId);
        console.log('手动刷新自定义字段完成');
      }
    }
  }
  defineExpose({
    setFormValues,
    setIsUpdate,
    resetForm,
    resetFields,
    getCategoryId,
    refreshCustomFields,
  });
</script>

<style lang="less" scoped>
  .custom-fields-container {
    margin: 16px 0;
  }

  .category-section {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
  }

  .category-section h3 {
    margin-top: 0;
    margin-bottom: 16px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
  }

  .fields-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 12px;
  }

  .field-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
  }

  .field-item label {
    font-weight: 500;
    width: 120px;
    margin-right: 12px;
    color: #666;
  }

  .field-item span {
    flex: 1;
    color: #333;
  }
</style>
